<style lang="less" scoped>
    @import '~assets/less/login';
</style>
<template>
    <div class="wrapper">
        <div class="login">
            <Card :bordered="false">
                <h2 class="title">{{ title }}</h2>
                <Form ref="form" :model="form" :rules="rules">
                    <Form-item prop="username">
                        <Input v-model.trim="form.username" placeholder="请输入用户名"></Input>
                    </Form-item>
                    <Form-item prop="password">
                        <Input v-model.trim="form.password" @on-enter="handleLogin()" type="password" placeholder="请输入密码，密码长度不能小于6位"></Input>
                    </Form-item>
                    <Form-item>
                        <Button type="primary" size="large" :loading="logining" @click.native="handleLogin()" long>
                            <span v-if="!logining">登录</span>
                            <span v-else>登录中...</span>
                        </Button>
                    </Form-item>
                </Form>
            </Card>
        </div>
    </div>
</template>
<script>
    import * as constants from 'src/AppConstants'
    import cache from 'commons/cache'
    import {mapActions} from 'vuex'

    export default {
        data(){
            return {
                logining: false,
                title: constants.APP_TITLE,
                form: {
                    username: 'admin',
                    password: '123456',
                },
                rules: {
                    username: [{
                        required: true,
                        message: '请填写用户名',
                        trigger: 'blur'
                    }],
                    password: [{
                        required: true,
                        message: '请填写密码',
                        trigger: 'blur'
                    }, {
                        type: 'string',
                        min: 6,
                        message: '密码长度不能小于6位',
                        trigger: 'blur'
                    }]
                }
            }
        },
        methods: {
            ...mapActions(["login"]),
            handleLogin() {
                let valid = false
                this.$refs['form'].validate(function(v){
                    valid = v
                });
                if (!valid) {
                    this.$Message.error('表单验证失败！')
                    return
                }
                this.logining = true
                this.login(this.form).then((data) => {
                    this.logining = false
                    console.log("登录成功", data)
                    this.$Message.success('登录成功')
                    this.$router.push(this.$route.query.from || JSON.parse(cache.getValue(constants.CACHE_USER_NAV))[0].path)
                }).catch((err) => {
                    console.warn('登录失败', err)
                    this.logining = false
                })
            }
        }
    }
</script>
